package com.linkage.common.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkage.common.base.RequestInfo;
import com.linkage.common.base.ResponseInfo;
import com.linkage.common.config.RedisConfig;
import com.linkage.common.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("请求路径为："+request.getRequestURI());
        if (getAllowResourceService().contains(request.getServletPath())) {
            filterChain.doFilter(request, response);
        } else {
            HttpServletRequest requestWrapper2 = new MyRequestWrapper(request);
            String jsonString = ((MyRequestWrapper) requestWrapper2).getBodyString();
            RequestInfo requestInfo = JSONObject.parseObject(jsonString, RequestInfo.class);
            String token = requestInfo.getBase().getUsertoken();
            try {
                if(StrUtil.isNotEmpty(token)){
                    String personClass = token.split(":")[2];
                    if(StrUtil.equals("GLY-45-4",personClass)){
                        if(redisUtils.hasKey(token)){
                            redisUtils.expire(token,600);
                            filterChain.doFilter(requestWrapper2,response);
                        }else{
                            responseOutWithJson(response, ResponseInfo.tokenError("token失效，请重新登录"));
                        }
                    }else {
                        filterChain.doFilter(requestWrapper2,response);
                    }
                }else{
                    responseOutWithJson(response, ResponseInfo.tokenError("token不存在，请重新登录"));
                }
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        }
    }

    protected void responseOutWithJson(HttpServletResponse response, Object responseObject) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(responseObject);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    private List<String> getAllowResourceService(){
        List<String> urlList =new ArrayList<>();
        urlList.add("/exter/login");
        urlList.add("/exter/manage/login");
        urlList.add("/exter/manage/loginOut");
        urlList.add("/common/upload");
        urlList.add("/common/sendSMS");
        //注册
        urlList.add("/exter/register");
        //忘记密码  修改
        urlList.add("/exter/forgetPwd");
        urlList.add("/exter/upload/userExcel");
        urlList.add("/train/queryListByPage");
        urlList.add("/train/queryTrainInfo");
        urlList.add("/problem/queryProblemList");
        urlList.add("/problem/queryProblemInfo");
        urlList.add("/banner/getList");
        urlList.add("/notice/getList");
        urlList.add("/notice/singleNoticeShow");
        urlList.add("/exter/dpt/queryDeptList");
        urlList.add("/event/getEventTypeList");
        return urlList;
    }
}
